<template>
  <div class="selector-menu">
    <template v-if="searchData.length > 0">
      <div
        class="menu-item"
        v-for="(item, index) of searchData"
        :key="index"
        @click="setItemValue(item)"
      >
        {{ item.text }}
      </div>
    </template>
    <NoDataTip v-else />
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import NoDataTip from './NoDataTip';

export default {
  name: 'SelectorMenu',
  components: {
    NoDataTip
  },
  props: {
    searchValue: String,
    data: {
      type: Array,
      default () {
        return [
          {
            id: 1,
            value: '1',
            text: '选项1'
          },
          {
            id: 2,
            value: '2',
            text: '选项2'
          },
          {
            id: 3,
            value: '3',
            text: '选项3'
          }
        ]
      }
    }
  },
  setup(props, { emit }) {
    const searchData = ref([]);

    onMounted(() => {
      searchData.value = props.data;
    });

    watch(() => {
      return props.searchValue;
    }, (value) => {
      filterData(value);
    })

    function filterData(value) {
      searchData.value = props.data.filter(item => {
        return item.text.toLowerCase().includes(value.toLowerCase());
      })
    }

    const setItemValue = (item) => {
      emit('setItemValue', item);
    }


    return {
      searchData,
      setItemValue,
    }
  }
}
</script>

<style lang="scss" scoped>
  .selector-menu {
    display: none;
    position: absolute;
    left: 0;
    top: 48px;
    width: 100%;
    background-color: #fff;
    box-shadow: 0 0 10px #ddd;
    border-radius: 5px;
    cursor: pointer;

    .menu-item {
      margin: 10px 0;
      height: 35px;
      line-height: 35px;
      color: #666;
      font-size: 14px;
      text-align: center;
      transition: background-color .2s linear;

      &:hover {
        background-color: #ededed;
      }
    }
  }
</style>